#include "UI/Widget/ValueGauge.h"

#include "AbilitySystemComponent.h"
#include "Components/ProgressBar.h"
#include "Components/TextBlock.h"

void UValueGauge::NativePreConstruct()
 {
 	Super::NativePreConstruct();
 	if(ProgressBar) ProgressBar->SetFillColorAndOpacity(BaseColor);
 }

void UValueGauge::SetAndBoundToGameplayAttribute(UAbilitySystemComponent* AbilitySystemComponent, const FGameplayAttribute& Attribute, const FGameplayAttribute& MaxAttribute)
{
	if(AbilitySystemComponent)
	{
		bool bGetAttribute;
		bool bGetMaxAttribute;
		float Value = AbilitySystemComponent->GetGameplayAttributeValue(Attribute,bGetAttribute);
		float MaxValue = AbilitySystemComponent->GetGameplayAttributeValue(MaxAttribute,bGetMaxAttribute);
		if (bGetAttribute && bGetMaxAttribute)
		{
			SetValue(Value,MaxValue);
		}

		//订阅属性的变化: 当指定游戏属性(Attribute)发生变化时，自动调用UValueGauge类的ValueChanged方法
		AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(Attribute).AddUObject(this, &UValueGauge::ValueChanged);
		AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(MaxAttribute).AddUObject(this, &UValueGauge::MaxValueChanged);
	}
}

void UValueGauge::SetBaseColor(FLinearColor NewBaseColor)
 {
 	BaseColor = NewBaseColor;
 	if(ProgressBar) ProgressBar->SetFillColorAndOpacity(BaseColor);
 }

void UValueGauge::ValueChanged(const FOnAttributeChangeData& ChangedData)
{
	SetValue(ChangedData.NewValue,CachedMaxValue);
}

void UValueGauge::MaxValueChanged(const FOnAttributeChangeData& ChangedData)
{
	SetValue(CachedValue,ChangedData.NewValue);
}


void UValueGauge::SetValue(float NewValue, float NewMaxValue)
 {
 	if (NewMaxValue == 0)
 	{
 		// UE_LOG(LogTemp, Warning, TEXT("Value Gauge: %s - Max value is 0"), *GetName());
 		return;
 	}

	CachedValue = NewValue;
	CachedMaxValue = NewMaxValue;
    
 	const float Percent = FMath::Clamp(NewValue / NewMaxValue, 0.0f, 1.0f);

	// 决定使用基础色还是低值色
	// FLinearColor TargetColor = Percent >= LowValueThreshold ? BaseColor : LowValueColor;
	FLinearColor TargetColor = Percent >= LowValueThreshold ?
		FMath::Lerp(LowValueColor, BaseColor, Percent):FMath::Lerp(BaseColor, LowValueColor, Percent / LowValueThreshold);
    	
	// 计算亮度变化（低值时反转亮度变化方向）
	float Brightness = Percent >= LowValueThreshold ? 
		FMath::Lerp(MinBrightness, MaxBrightness, Percent) :
		FMath::Lerp(MaxBrightness, MinBrightness, Percent / LowValueThreshold);
    
 	FLinearColor CurrentColor = TargetColor;
 	CurrentColor.R *= Brightness;
 	CurrentColor.G *= Brightness;
 	CurrentColor.B *= Brightness;
    
 	if(ProgressBar)
 	{
 		ProgressBar->SetPercent(Percent);
 		ProgressBar->SetFillColorAndOpacity(CurrentColor);
 	}
    
 	if (ValueText)
 	{
 		ValueText->SetText(FText::Format(
			 FTextFormat::FromString("{0}/{1}"),
			 FText::AsNumber(NewValue),
			 FText::AsNumber(NewMaxValue)
		 ));
 	}
 }
